<template>
  <el-dialog :close-on-click-modal="false" append-to-body :title="title" :visible.sync="visible" width="800px">
    <div class="add-form">
      <el-form ref="form" :model="form" label-width="120px" :disabled="type === 'view'">
        <el-form-item label="贺卡名称" prop="name" :rules="[
          { required: true, message: '请输入贺卡名称', trigger: 'blur' },
        ]">
          <el-input class="w-300" v-model="form.name" placeholder="请输入贺卡名称"></el-input>
        </el-form-item>
        <el-form-item label="贺卡内容" prop="content" :rules="[
          { required: true, message: '请输入贺卡内容', trigger: 'blur' },
        ]">
          <el-input type="textarea" rows="6" v-model="form.content" placeholder="请输入贺卡内容"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="submit" v-show="type !== 'view'" :loading="loading">{{ loading ? '提交中...' :
          '提交'
      }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { saveOrderCard, updateOrderCard } from '@/api/system/greetingCard'
export default {
  components: {
  },
  data() {
    return {
      visible: false,
      loading: false,
      type: 'add',
      form: {
        "name": "",
        "content": "",
      },
    }
  },
  computed: {
    title() {
      const textMap = {
        'add': '新增贺卡',
        'edit': '编辑贺卡',
        'view': '查看贺卡'
      }
      return textMap[this.type]
    }
  },
  methods: {
    show({ type, data }) {
      this.type = type
      this.visible = true
      if (data) {
        this.form = {
          ...data,
        }
      } else {
        this.clearForm()
      }
    },
    clearForm() {
      this.form = {
        "name": "",
        "content": "",
      }
      this.$refs.form && this.$refs.form.clearValidate()
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const request = this.type === 'add' ? saveOrderCard : updateOrderCard
          this.loading = true
          request(this.getParams()).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: `提交成功！`
              })
              this.visible = false
              this.$emit('submit')
            } else {
              this.$message({
                type: 'error',
                message: res.data.msg
              })
            }
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    getParams() {
      const params = {
        id: this.type === 'edit' ? this.form.id : undefined,
        "name": this.form.name,
        "content": this.form.content,
      }
      return params
    },
  },
  created() {
  }
}
</script>

<style lang="scss" scoped>
.add-form {}
</style>
